package com.baizhi.lucenceservice.impl;





import com.baizhi.dao.CmfzArticleDao;
import com.baizhi.entity.CmfzArticle;
import com.baizhi.lucenceservice.LucenceService;
import com.baizhi.lucenceutil.LucenceUtil;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: renpu
 * @Date: 2019/3/12 19:51
 * @Description:
 */
@Service
@Transactional
public class LucenceServiceImpl implements LucenceService {

    @Autowired
    private CmfzArticleDao cmfzArticleDao;


    @Override
    public boolean addCmfzArticle(CmfzArticle cmfzArticle) {

        IndexWriter indexWriter=null;

        if(cmfzArticle!=null) {
            Document document = new Document();
            //将实体类的对象封装到Documet对象中；
            document.add(new StringField("articleId",cmfzArticle.getArticleId()+"", Field.Store.YES));
            document.add(new TextField("articleName", cmfzArticle.getArticleName(), Field.Store.YES));
            document.add(new TextField("articleImage", cmfzArticle.getArticleImage(), Field.Store.YES));
            document.add(new TextField("articleContent", cmfzArticle.getArticleContent(), Field.Store.YES));
            document.add(new IntField("guruId", cmfzArticle.getGuruId(), Field.Store.YES));
             indexWriter = LucenceUtil.getIndexWriter();
            try {
                indexWriter.addDocument(document);
            } catch (IOException e) {
                e.printStackTrace();
            }
            LucenceUtil.indexCommit(indexWriter);
            LucenceUtil.indexClose(indexWriter);
            return true;
        }else{
            LucenceUtil.indexRollerBack(indexWriter);
            return false;
        }
    }

    @Override
    public boolean addCmfzArticles(List<CmfzArticle> cmfzArticles) {
        IndexWriter indexWriter=null;
        if(cmfzArticles!=null){
        ArrayList<Document> documents = new ArrayList<>();
        for (CmfzArticle cmfzArticle : cmfzArticles) {
            Document document = new Document();
            //将实体类的对象封装到Documet对象中；
            document.add(new StringField("articleId", cmfzArticle.getArticleId()+"", Field.Store.YES));
            document.add(new TextField("articleName", cmfzArticle.getArticleName(), Field.Store.YES));
            document.add(new TextField("articleImage", cmfzArticle.getArticleImage(), Field.Store.YES));
            document.add(new TextField("articleContent", cmfzArticle.getArticleContent(), Field.Store.YES));
            document.add(new IntField("guruId", cmfzArticle.getGuruId(), Field.Store.YES));
            documents.add(document);
            try {
                 indexWriter = LucenceUtil.getIndexWriter();
                indexWriter.addDocuments(documents);
                LucenceUtil.indexCommit(indexWriter);
                LucenceUtil.indexClose(indexWriter);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
        }else{
            LucenceUtil.indexRollerBack(indexWriter);
            return false;
        }
    }

    @Override
    public List<CmfzArticle> queryByKeyWord(String keyword) {
        List<CmfzArticle> list=null;
        IndexSearcher indexSearcher=LucenceUtil.getIndexSeacher();
        try {
            list=new ArrayList<>();
            Query query = LucenceUtil.getQuery(keyword);

            QueryScorer queryScorer = new QueryScorer(query);

            //负责渲染色彩的高亮器；
            SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<font color='red'>","</font>");
            Highlighter highlighter=new Highlighter(formatter,queryScorer);
            TopDocs topDocs = indexSearcher.search(query, 100);

            ScoreDoc[] scoreDocs = topDocs.scoreDocs;
            for (int i = 0; i <scoreDocs.length;i++) {

                int doc = scoreDocs[i].doc;
                Document doc1 = indexSearcher.doc(doc);

                int articleId=Integer.valueOf(doc1.get("articleId"));
                String articleName=doc1.get("articleName");
                String articleImage=doc1.get("articleImage");
                String articleContent=doc1.get("articleContent");
                int guruId=Integer.valueOf(doc1.get("guruId"));
                String articleNameT=highlighter.getBestFragment(LucenceUtil.analyzer,"artcicleName",articleName);
                String articleContentT=highlighter.getBestFragment(LucenceUtil.analyzer,"articleContent",articleContent);
                list.add(new CmfzArticle(articleId,articleNameT,articleImage,articleContentT,guruId));
            }
            System.out.println(list);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidTokenOffsetsException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public boolean deleteAll() {
        IndexWriter indexWriter = LucenceUtil.getIndexWriter();
        try {
            indexWriter.deleteAll();
            LucenceUtil.indexCommit(indexWriter);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        LucenceUtil.indexRollerBack(indexWriter);
        return false;
    }

    @Override
    public boolean deleteById(int id) {

        IndexWriter indexWriter = LucenceUtil.getIndexWriter();
        try {
            indexWriter.deleteDocuments(new Term("articleId",id+""));
            LucenceUtil.indexCommit(indexWriter);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        LucenceUtil.indexRollerBack(indexWriter);
        return false;
    }

    @Override
    public boolean updateCmfzArticleById(CmfzArticle cmfzArticle) {
        IndexWriter indexWriter=null;
        int id=cmfzArticle.getArticleId();
        Document document = new Document();
        //将实体类的对象封装到Documet对象中；
        document.add(new StringField("articleId", cmfzArticle.getArticleId()+"", Field.Store.YES));
        document.add(new StringField("articleName", cmfzArticle.getArticleName(), Field.Store.YES));
        document.add(new TextField("articleImage", cmfzArticle.getArticleImage(), Field.Store.YES));
        document.add(new TextField("articleContent", cmfzArticle.getArticleContent(), Field.Store.YES));
        document.add(new IntField("guruId", cmfzArticle.getGuruId(), Field.Store.YES));
         indexWriter = LucenceUtil.getIndexWriter();
            try {
                indexWriter.updateDocument(new Term("articleId",id+""),document);
                LucenceUtil.indexCommit(indexWriter);
                return true;
            } catch (IOException e) {
                e.printStackTrace();
                LucenceUtil.indexRollerBack(indexWriter);
                return false;
            }
    }

    @Override
    public boolean resetIndex() {
        try {
            IndexWriter indexWriter = LucenceUtil.getIndexWriter();
                indexWriter.deleteAll();
            List<CmfzArticle> cmfzArticles=cmfzArticleDao.selectAllArtilce();
            ArrayList<Document> documents = new ArrayList<>();
            for (CmfzArticle cmfzArticle : cmfzArticles) {
                Document document = new Document();
                //将实体类的对象封装到Documet对象中；
                document.add(new StringField("articleId", cmfzArticle.getArticleId()+"", Field.Store.YES));
                document.add(new StringField("articleName", cmfzArticle.getArticleName(), Field.Store.YES));
                document.add(new TextField("articleImage", cmfzArticle.getArticleImage(), Field.Store.YES));
                document.add(new TextField("articleContent", cmfzArticle.getArticleContent(), Field.Store.YES));
                document.add(new IntField("guruId", cmfzArticle.getGuruId(), Field.Store.YES));
                documents.add(document);
            }
            indexWriter.addDocuments(documents);
            LucenceUtil.indexCommit(indexWriter);
            LucenceUtil.indexClose(indexWriter);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
